import { useContext, useEffect, useRef, useState } from 'react'
import { AppContext } from '@/pages/App/context'
import { optionProps, UpdateAddressFormDataProps } from './interface'
import { FormItem, Message, Modal } from '@kedacom/react-next'
import { alertModal } from '../Modal'
import { checkIsIP, checkMac, toFullIPV6Addr } from '@/utils/rules'
const useIndexHook = (receiveAddress: { ip: string; mac: string; moid?: string }[], selectAddress: Function) => {
	const AppData = useContext(AppContext)
	/**登录的用户的信息 */
	const userInfo = AppData.user
	const INPUT_WIDTH = 180
	const [otherAddress, setOtherAddress] = useState<UpdateAddressFormDataProps[]>([])
	const [allList, setAllList] = useState<{ ip: string; mac: string; moid?: string }[]>([])
	/**本地获取缓存地址 */
	let localAddress: string | null = localStorage.getItem('ip-mac_List')
	/**本地已有地址展示 */
	const [addressLocalList, setAddressLocalList] = useState<UpdateAddressFormDataProps[]>([])
	/**是否展示本地添加弹出框 */
	const [showLocalModal, setShowLocalModal] = useState<boolean>(false)
	/**本地弹出来已选选项 */
	const [groupValue, setGroupValue] = useState<number[]>([])
	/**本地添加选项 */
	const [groupOption, setGroupOption] = useState<optionProps[]>([])
	/**手动添加弹出框 */
	const [showManualModal, setShowManualModal] = useState<boolean>(false)
	/**手动添加弹出框数据 */
	const [manualForm, setManualForm] = useState<{ ip: string; mac: string }>({ ip: '', mac: '' })
	/**从本地添加函数 */
	const localAddAddress = () => {
		//判断现有本地地址展示，并将弹框中的已有数据进行disabled不可点展示
		freshCheckBox(addressLocalList)
		setShowLocalModal(true)
	}
	/**更新已有复选框数据 */
	const freshCheckBox = (addressLocalChoose: UpdateAddressFormDataProps[]) => {
		let resetDisabledList = []
		let resetGroupValue = []
		for (let groupKey = 0; groupKey < groupOption.length; groupKey++) {
			if (addressLocalChoose.find((item) => item.key === groupOption[groupKey].key)) {
				resetDisabledList.push({ ...groupOption[groupKey], disabled: true, height: 30 })
				resetGroupValue.push(groupKey)
			} else {
				resetDisabledList.push({
					...groupOption[groupKey],
					disabled: false,
					height: 30,
				})
			}
		}
		setGroupValue(resetGroupValue)
		setGroupOption(resetDisabledList)
	}
	/**本地添加返回弹出框 */
	const onCancelLocalModal = () => {
		setShowLocalModal(false)
	}
	/**确认本地添加 */
	const addAddressClick = () => {
		let addressLocalListAll: UpdateAddressFormDataProps[] = []
		let changeLocal: { ip: string; mac: string; key?: string }[] = []

		groupValue.map((item) => {
			let ipMacList = groupOption[item].key.split(';')
			if (!groupOption[item].disabled) {
				changeLocal.push({ ip: ipMacList[0], mac: ipMacList[1] })
			}
			addressLocalListAll.push({ ip: ipMacList[0], mac: ipMacList[1], key: groupOption[item].key })
			return ''
		})
		if (!addClickAddressCheck(addressLocalListAll, otherAddress)) {
			return false
		}
		setShowLocalModal(false)
		setAddressLocalList(addressLocalListAll)
		summaryData(otherAddress, addressLocalListAll, 'add', changeLocal)
	}
	/**汇总数据 */
	const summaryData = (
		otherAddressList: UpdateAddressFormDataProps[],
		addressLocalListAll: UpdateAddressFormDataProps[],
		type: string,
		changeList: { ip: string; mac: string; key?: string }[]
	) => {
		let allLocalList = addressLocalListAll.map((item) => {
			let ipMacList = item.key.split(';')
			return { ip: toFullIPV6Addr(ipMacList[0]), mac: ipMacList[1].replace(/-/g, ':').toUpperCase() }
		})
		let otherList = otherAddressList.map((item) => {
			let ipMacList = item.key.split(';')
			return { ip: toFullIPV6Addr(ipMacList[0]), mac: ipMacList[1].replace(/-/g, ':').toUpperCase() }
		})
		//根据提供函数传出数据
		selectAddress(allLocalList.concat(otherList), type, changeList)
	}
	/**更新复选框数据 */
	const checkBoxGroupChange = (key: number[]) => {
		setGroupValue(key)
	}
	/**删除其他地址 */
	const delOtherClick = (value: UpdateAddressFormDataProps) => {
		let m = Modal.confirm({
			width: 480,
			height: 300,
			content: (
				<div>
					<div>确定删除该IP&MAC地址？</div>
					<div style={{ paddingTop: '10px' }}>
						<span>IP地址： {value.ip}</span>
						<span style={{ paddingLeft: '10px' }}>MAC地址： {value.mac}</span>
					</div>
				</div>
			),
			onOk: () => {
				let otherAddressList = otherAddress.filter((item, index) => item.key !== value.key)
				setOtherAddress(otherAddressList)
				summaryData(otherAddressList, addressLocalList, 'del', [value])
				// Message.info('删除成功')
				m.hide()
			},
			onCancel: () => {
				m.hide()
			},
		})
	}

	/**删除本地地址 */
	const delLocalClick = (value: UpdateAddressFormDataProps) => {
		let m = Modal.confirm({
			width: 500,
			content: (
				<div>
					<div>确定删除该IP&MAC地址？</div>
					<div>
						<span>IP地址： {value.ip}</span>
						<span style={{ padding: '30px' }}>MAC地址： {value.mac}</span>
					</div>
				</div>
			),
			onOk: () => {
				let resetAddressList = addressLocalList.filter((item, index) => item.key !== value.key)
				setAddressLocalList(resetAddressList)
				freshCheckBox(resetAddressList)
				summaryData(otherAddress, resetAddressList, 'del', [value])
				// Message.info('删除成功')
				m.hide()
			},
			onCancel: () => {
				m.hide()
			},
		})
	}

	/** 添加地址检测*/
	const addClickAddressCheck = (localList: any, otherList: any) => {
		let checked = true
		// groupValue.length +
		if (localList.length + otherList.length > 10) {
			alertModal({ msg: '绑定ip，mac地址最多十条' })
			checked = false
		}
		return checked
	}
	/**手动添加 */
	const manualAddAddress = () => {
		setManualForm({ ip: '', mac: '' })
		setShowManualModal(true)
	}
	/**手动添加返回 */
	const onCancelManualModal = () => {
		setShowManualModal(false)
	}
	/**手动添加数据变化 */
	const onManualFormCheck = (value: string, type: string) => {
		setManualForm({ ...manualForm, [type]: value.trim() })
	}
	/**手动添加确认 */
	const addManualAddressClick = () => {
		if (
			!addClickAddressCheck(addressLocalList, [
				...otherAddress,
				{ ...manualForm, key: manualForm.ip + ';' + manualForm.mac },
			])
		) {
			return false
		}
		if (checkIpMac([manualForm])) {
			let resetOtherAddress = [...otherAddress, { ...manualForm, key: manualForm.ip + ';' + manualForm.mac }]
			setOtherAddress(resetOtherAddress)
			setShowManualModal(false)
			summaryData(resetOtherAddress, addressLocalList, 'add', [manualForm])
		}
	}
	/**ip mac校验 */
	const checkIpMac = (newAddressFormData: string | any[]) => {
		let rule = true
		for (var index = 0; index < newAddressFormData.length; index++) {
			let item = newAddressFormData[index]
			if (!item.ip || !item.mac) {
				alertModal({
					msg: 'IP,MAC需全部填写',
				})
				rule = false
				break
			}
			if (!checkIsIP(item.ip)) {
				alertModal({
					msg: 'IP地址填写错误',
				})
				rule = false
				break
			}
			if (!checkMac(item.mac)) {
				alertModal({
					msg: 'MAC地址填写错误',
				})
				rule = false
				break
			}
			/**唯一性校验，ip+mac为一条数据，不可重复 */
			let allAddressList = otherAddress.concat(addressLocalList)
			for (var j = 0; j < allAddressList.length; j++) {
				if (
					toFullIPV6Addr(manualForm.ip) === toFullIPV6Addr(allAddressList[j].ip) &&
					manualForm.mac.replace(/-/g, ':').toUpperCase() ===
						allAddressList[j].mac.replace(/-/g, ':').toUpperCase()
				) {
					console.log('===========')
					alertModal({
						msg: '请勿重复添加数据',
					})
					return false
				}
			}
		}
		return rule
	}
	/**初次进入获取数据分类展示 */
	useEffect(() => {
		let resetRecvList = []
		let localRecvList = []
		let otherRecvList = []
		for (let recvKey = 0; recvKey < receiveAddress.length; recvKey++) {
			let key = receiveAddress[recvKey].ip + ';' + receiveAddress[recvKey].mac || ''
			resetRecvList.push({
				ip: receiveAddress[recvKey].ip,
				mac: receiveAddress[recvKey].mac,
				key: key,
				moid: receiveAddress[recvKey].moid || '',
			})
			if (groupOption.find((item) => item.key === key)) {
				localRecvList.push({
					ip: receiveAddress[recvKey].ip,
					mac: receiveAddress[recvKey].mac,
					key: key,
					moid: receiveAddress[recvKey].moid,
				})
			} else {
				otherRecvList.push({
					ip: receiveAddress[recvKey].ip,
					mac: receiveAddress[recvKey].mac,
					key: key,
					moid: receiveAddress[recvKey].moid,
				})
			}
		}
		setOtherAddress(otherRecvList)
		setAddressLocalList(localRecvList)
		setAllList(resetRecvList)
	}, [receiveAddress])
	const freshGroup = (localList: string | any[]) => {
		let resetOptionList = []
		for (let k = 0; k < localList.length; k++) {
			if (
				localList[k].ip !== '127.0.0.1' &&
				localList[k].ip !== '0.0.0.0' &&
				toFullIPV6Addr(localList[k].ip) !== '0000:0000:0000:0000:0000:0000:0000:0000' &&
				localList[k].mac !== '00:00:00:00:00:00'
			) {
				resetOptionList.push({
					label: (
						<FormItem className="bind-group-text">
							<FormItem className="address-group-form-text" label="IP地址">
								<span className="address-group-form-span" title={localList[k].ip}>
									{localList[k].ip}
								</span>
							</FormItem>
							<FormItem className="address-group-form-text" label="MAC地址">
								<span className="address-group-form-span" title={localList[k].mac}>
									{localList[k].mac}
								</span>
							</FormItem>
						</FormItem>
					),
					value: k,
					key: localList[k].ip + ';' + localList[k].mac,
					width: 450,
					height: 30,
					moid: localList[k].moid,
				})
			}
		}
		setGroupOption(resetOptionList)
	}
	useEffect(() => {
		if (localAddress) {
			let localList = JSON.parse(localAddress)
			freshGroup(localList)
		}
	}, [localAddress])
	return {
		INPUT_WIDTH,
		addressLocalList,
		otherAddress,
		showLocalModal,
		groupOption,
		groupValue,
		allList,
		localAddAddress,
		checkBoxGroupChange,
		addAddressClick,
		onCancelLocalModal,
		delOtherClick,
		delLocalClick,
		manualAddAddress,
		showManualModal,
		onCancelManualModal,
		manualForm,
		onManualFormCheck,
		addManualAddressClick,
	}
}
export default useIndexHook
